/**
 * Copyright © 2018,  Network Co.,Ltd. All rights reserved.  PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.james.sms.conf;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import java.io.IOException;
import javax.annotation.PostConstruct;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.context.annotation.Configuration;

/**
 * ClassName:com.james.sms Description: ${DESCRIPTION}
 *
 * Date: 2018/7/6 17:55
 *
 * @author James
 * @version 1.0.0
 */
@Configuration
@AutoConfigureAfter(QCloudSmsConfig.class)
@ConditionalOnProperty(prefix = "sms.qcloud.config", value = "test-connection")
@ConditionalOnSingleCandidate(SmsSingleSender.class)
public class QCloudSmsValidatorConfig {

    private final SmsSingleSender smsSingleSender;

    private final QCloudSmsTestProperties qCloudSmsTestProperties;

    public QCloudSmsValidatorConfig(SmsSingleSender smsSingleSender, QCloudSmsTestProperties qCloudSmsTestProperties) {
        this.smsSingleSender = smsSingleSender;
        this.qCloudSmsTestProperties = qCloudSmsTestProperties;
    }

    @PostConstruct
    public void validateConnection() {
        SmsSingleSenderResult result = null;
        try {
            result = smsSingleSender.send(qCloudSmsTestProperties.getType(), qCloudSmsTestProperties.getNationCode(),
                qCloudSmsTestProperties.getPhoneNumber(), qCloudSmsTestProperties.getMsg(),
                qCloudSmsTestProperties.getExtend(), qCloudSmsTestProperties.getExt());
        } catch (HTTPException | IOException e) {
            e.printStackTrace();
        }
        if (null == result) {
            throw new RuntimeException("sms server is error,result is null");
        }
        if (0 == result.result) {
            throw new RuntimeException("sms server is error,result = " + result.result);
        }
    }
}
